
const db = require('../../dbContorller/curd');
const Results = require('../../config/results');


module.exports = {
  async getGoodsByLimit(req, res, next) {
    // select * from goods as g limit 10,10  从第几个开始 展示多少个
    let num = parseInt(req.query.num) //第几页
    let size = parseInt(req.query.size) //每页多少个
    let id = req.query.id
    let data, sql, where, limit;

    if (num.toString() === 'NaN' || size.toString() === 'NaN') {
      return res.status(500).json(Results.fail(500, '页码和数量error！', {num: num, size: size}))
    }
    //因为id没带引号导致报错 UnhandledPromiseRejection
    limit = `limit ${num * size - size},${size}`
    if (id) {
      where = `where goods_id = ${id}`
    } else {
      where = ``
    }

    sql = `select * from songshu.goods ${where} ${limit};`

    data = await db.executeCustom(sql)
    return res.status(200).json(Results.success(200, data.message, data.results))
  },

  getGoodsByKeyWords: async function (req, res, next) {
    let {keywords} = req.params
    let {num, size} = req.query
    let data;
    if (Object.prototype.toString.call(keywords) !== '[object String]') {
      return res.status(500).json(Results.fail(500, '请检查参数类型！', null))
    }
    data = await db.Find('goods', 'goods_name', keywords, num, size)
    return res.status(200).json(Results.success(200, data.message, data.results))
  },
  getGoodsTypes: async function (req, res, next) {
    try {
      let a = await db.executeCustom('select distinct goods_type from songshu.goods;')

      res.json(Results.success(200, 'ok', a.results))
    } catch ({error}) {
      res.json(Results.fail(500, error.message, null));
    }

  },
  async updateGoodsById(req, res, next) {
    try {
      let goodsObj = req.body.goods
      let data = await db.Update('goods', goodsObj, 'goods_id', goodsObj.goods_id)
      res.status(200).json(Results.success(200, '更新成功！', data))
    } catch ({error}) {
      res.json(Results.fail(500, error.message, error));

    }
  },
  async addGoods(req, res, next) {
    try {
      let goodsObj = req.body.goods
      let data = await db.Add('goods', goodsObj)
      res.status(200).json(Results.success(200, '新增成功！', data))
    } catch (error) {
      console.log(error)
      res.json(Results.fail(500, error.message, null));
    }
  }
}
